package com.data.service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.config.dao.EquStateConfigDao;
import com.config.dao.EquipmentDao;
import com.config.dao.LineConfigDao;
import com.config.entity.EquStateConfig;
import com.config.entity.Equipment;
import com.config.entity.LineConfig;
import com.data.dao.BaseDataDao;
import com.data.dao.StateMinDao;
import com.data.entity.BaseData;
import com.data.entity.StateMin;

@Service("stateMinService")
public class StateMinServiceImpl implements StateMinService{
	@Resource(name="baseDataDao")
	private BaseDataDao baseDataDao;
	@Resource(name="lineConfigDao")
	private LineConfigDao lineConfigDao;
	@Resource(name="equipmentDao")
	private EquipmentDao equipmentDao;
	@Resource(name="equStateConfigDao")
	private EquStateConfigDao equStateConfigDao;
	@Resource(name="stateMinDao")
	private StateMinDao stateMinDao;
	/**
	 * 存储设备状态半小时数据
	 * @param belongTime
	 */
	@Override
	public void saveStateMin(Date belongTime) {
		DecimalFormat  df=new DecimalFormat ("0.0");
		SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String beforeTime=sdf.format(new Date(belongTime.getTime()-30*60*1000));
		List<LineConfig> lines=lineConfigDao.findAllLine();
		List<EquStateConfig> states=equStateConfigDao.findAll();
		if(lines.size()!=0){
			for(LineConfig line:lines){
    			List<Equipment> equs=equipmentDao.listByLine(line.getId());
    			if(equs.size()!=0){
    				for(Equipment e:equs){
    					if(states.size()!=0){
    						for(EquStateConfig state:states){
    							List<BaseData>bases=baseDataDao.getBaseDataByPower(e.getEquNo(), beforeTime, sdf.format(belongTime), state.getHighValue(), state.getLowValue());
    							if(bases.size()!=0){
	    							StateMin min=stateMinDao.getStateMinByDate(e.getId(), state.getStateType(), sdft.format(belongTime));
									boolean isNew=false;
									if(min==null){
										min=new StateMin();
										min.setEquId(e.getId());
										min.setStateType(state.getStateType());
										min.setBelongTime(belongTime);
										min.setDuration(0.0);
										min.setRelativeComp(0.0);
										isNew=true;
									}
										min.setDuration((double)bases.size());
										min.setRelativeComp(Double.parseDouble(df.format(bases.get(bases.size()-1).getP_engry()-bases.get(0).getP_engry())));
									if(isNew){
										if(min.getRelativeComp()!=0.0){
											 stateMinDao.save(min);
										}
		    						}else{
		    							    stateMinDao.update(min);
		    						}
	    						}
	    					}
	    				}
					}
				}
			}
		}
	}
}
